import axios from 'axios'
import Qs from 'qs'
import { Toast } from 'vant'; 

// 默认超时设置
axios.defaults.timeout = 50000;

// 相对路径设置
if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = 'http://10.251.9.11'
  window.localStorage.setItem('ip', 'http://10.251.9.11');
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = ''
  window.localStorage.setItem('ip', window.location.protocol+"//"+window.location.host);
}

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

//http request 拦截器
axios.interceptors.request.use(
  config => {
    
    return config;
  },
  err => {
    return Promise.error(err)
  }
);

//http response 拦截器
axios.interceptors.response.use(
  response => {
    //一些统一code的返回处理
    if(response.data.code === 501){
      // 登录验证
      //做了个示例跳转项目中登录，并记录下相对路径
      router.push({
        name:'login',//从哪个页面跳转
        query:{
          retUrl:window.location.href.split('#')[1] || '',
          is_new_user_url:1
        }
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
);


// get 请求
export function get ({
  url,
  params = {}
}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params
    }).then((res) => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

// post请求
export function post ({
  url,
  data = {},
  params = {}
}) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'post',
      // 发送的数据
      data,
      // url参数
      params

    }).then(res => {
      resolve(res.data)
    })
  })
}